/*
	自产配件保修申请
*/
public without sharing class AccessoryWarrantyController {
   public String msg {get; private set;}
   public Boolean isErr {get; private set;}
   public Boolean isSuccess {get;private set ;}

   public String backId {get;private set;}

   public String dataJson {get;private set;}
   public String saveJson {get; set;}
  // public String searchJson {get; set;}
   public  AccessoryWarranty__c aw {get;private set;} 
   public List<AccessoryWarrantyDetails__c> awdList {get;private set;}
   public String companyName {get;private set;}
   public String installDate {get;private set;}
   private  Map<String,DataUtil.SObjectBean> stageObjectMap;
   private Boolean isNew;
   public Boolean isEngineer {get; private set;}
   public  Boolean isDealer {get; private set;}//是否为经销商配件借出
    public Boolean isAssit {get; private set;}//当前操作人是否为助理

   public AccessoryWarrantyController() {
        backId  = System.currentPageReference().getParameters().get('id');
        aw = new AccessoryWarranty__c();
        stageObjectMap = new Map<String,DataUtil.SObjectBean>();
        isNew = true;


   }

   public void pdfRerender(){
   		aw = [select Id,RelatedWorkOrder__c,RelatedWorkOrder__r.Name ,Company__c,InstrumentName__c,
         InstrumentType__c,SerialNo__c,UsingCustomer__c,Department__c,InstallDate__c,Guaranteed__c,
         DepartmentContact__c,ContactNumber__c,AlarmCode__c
           from AccessoryWarranty__c where Id=:backId];

         installDate = aw.InstallDate__c == null ? '' : Datetime.newInstance(aw.InstallDate__c, Time.newInstance(0, 0, 0, 0)).format('yyyy年MM月dd日');
         companyName = ImportObject.getPicklistValues('AccessoryWarranty__c', 'Company__c', true).get(aw.Company__c);

   		awdList = new List<AccessoryWarrantyDetails__c> ();
   		awdList = [select   DamagedPartsNumber__c, ReplaceSerialNumber__c ,Parts__r.ProductName__c,Parts__r.NCCode__c  from AccessoryWarrantyDetails__c where AccessoryWarranty__c =:backId ];
   		
   		if(awdList.size() < 4){
   			Integer cnt = 4-awdList.size();
   			for (Integer i = 0 ;i < cnt; i ++ ) {
   				awdList.add(new AccessoryWarrantyDetails__c());
   			}
   		}

   }

   public void init(){



   		try {

             User u  = [select Id,EngineeringAssistant__c,ClientCode__c ,Profile.Name from User where Id=:UserInfo.getUserId()];
             isEngineer  = u.Profile.Name.contains('工程');
             isAssit = u.EngineeringAssistant__c;
             
             String accNumber = '';
           WorkOrder__c wo  = null;
   			if(Id.valueOf(backId).getSobjecttype() == WorkOrder__c.Sobjecttype ){
   				     
   				     aw.RelatedWorkOrder__c = backId;
               wo = [select Case__r.Status,Id ,NotificationAssistant__c,ServiceManufacture__r.EndDate__c,ServiceManufacture__r.Product__r.Brand__c ,InventoryOrganization__c, Technician__r.ClientCode__c  from WorkOrder__c where Id=:backId];
             //if(wo.Case__r.Status == '关闭' ) throw new DmlException('个案已关闭不能新建配件保修申请!');
                if(wo.NotificationAssistant__c == null && [select count() from WorkOrderProduct__c where WorkOrder__c =:backId] >0 )throw new DmlException('工单未通知助理,不能申请!');

              if(wo.ServiceManufacture__r.Product__r.Brand__c  == null || ! MaccuraBrandUtil.maccura.contains(wo.ServiceManufacture__r.Product__r.Brand__c) )throw new DmlException('工单的服务仪器不是迈克品牌不能申请!');
               if(wo.InventoryOrganization__c == null) throw new DmlException('工单的申请库存组织不能为空!');
               aw.Company__c = wo.InventoryOrganization__c;
               isNew = true;
               isDealer = wo.Technician__r.ClientCode__c  != null;
               accNumber =  wo.Technician__r.ClientCode__c;
              

   			}else if(Id.valueOf(backId).getSobjecttype() == AccessoryWarranty__c.Sobjecttype){
          isNew = false;
   				aw = [select Id,RelatedWorkOrder__c ,RelatedWorkOrder__r.Technician__r.ClientCode__c,Status__c from AccessoryWarranty__c where Id=:backId];
           wo = [select  ServiceManufacture__r.EndDate__c from WorkOrder__c where Id=:aw.RelatedWorkOrder__c  ];
          isDealer = aw.RelatedWorkOrder__r.Technician__r.ClientCode__c  != null;
          accNumber =  aw.RelatedWorkOrder__r.Technician__r.ClientCode__c;
           Boolean isAssit = [select EngineeringAssistant__c from User where Id=:UserInfo.getUserId()].EngineeringAssistant__c;
          if(!isAssit && (aw.Status__c == '审批中' || aw.Status__c == '已批准') )throw new DmlException('配件保修申请'+aw.Status__c +',不能修改!');


   			}else{
   		    	throw new DmlException('打开页面异常!');
   			}

        boolean isExpired = wo.ServiceManufacture__r.EndDate__c == null  ||  wo.ServiceManufacture__r.EndDate__c.addYears(1).daysBetween(System.today())>=0 ;
        if(!isAssit && isExpired)throw new DmlException('超过保修日期或没有仪器安装日期不能申请!');
        List<Account> accs = [select Id ,Name from Account where AccountNumber =:accNumber];
          if(accs.isEmpty() && isDealer ) throw new DmlException('请联系管理员维护用户信息的对应客户编码!');


   			Map<String , Object> dataMap = new Map<String,Object>();
   			dataMap.put('detail', getDetails());
   			dataMap.put('search', getSearchs());

                  //字段
             Map<String,Set<String>> fieldsmap = getFields();
             //字段详情
             Map<String, List<DataUtil.FieldBean>> fbMap = DataUtil.getFieldsBean(fieldsmap,stageObjectMap);
            
            //字段赋值
             Map<String,List<DataUtil.FieldBean>> fields = DataUtil.setFieldsValue(fbMap,DataUtil.getBaseInfo(fbMap,stageObjectMap) );
            
            for (DataUtil.FieldBean fb   :  fields.get('AccessoryWarranty__c')) {
                Map<String,Object> vMap  = new Map<String,Object>();

                if(fb.name == 'DocumentTypes__c')fb.value = '库存其他出库单';
             }
            dataMap.put('base',fields);
            dataMap.put('baseObject',DataUtil.getBaseObjectMap(stageObjectMap)); 
   			  dataJson = EncodingUtil.urlEncode(JSON.serialize(dataMap),'UTF-8');
   		    
   		}
   		catch (Exception e) {
   		    isErr = true ;
    		ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR ,e.getMessage()+e.getStackTraceString()));
   		}
   		
   }

   public Map<String,Set<String>>  getFields(){
        Map<String,Set<String>> fieldsMap  = new  Map<String,Set<String>>();
        
            DataUtil.SObjectBean sb = new DataUtil.SObjectBean();

            sb.title ='';
            sb.objname = 'AccessoryWarranty__c';
            sb.stype = DataUtil.getSObjectType( sb.objname);
            if(!isNew)sb.idvalue = backId;
            sb.type = 'base';
            if(!isNew)sb.condition = ' where Id =\''+backId +'\'';

            stageObjectMap.put( sb.objname,sb );
            //'InvoiceAccount__c',
            Set<String>  fields = new Set<String>{'DocumentTypes__c','FollowupProcessing__c','Remark__c',
               'Merchants__c','Phone__c','ReceivingRemarks__c','InstallmentSale__c','PhysicalDelivery__c'
            };
         
            fieldsMap.put( sb.objname, fields);
        
        return fieldsMap;
    }

   public void save(){
   		msg = '';
   		try {
            Map<String,Object> saveMap = ( Map<String,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));
   			
             Map<String,Set<String>> fieldsMap = getFields();
            Map<String,DataUtil.FieldBean> fbeanMap = DataUtil.getFieldsInfo(AccessoryWarranty__c.SObjecttype,fieldsMap.get('AccessoryWarranty__c'));


               Map<String,Object> obj = (Map<String,Object>) saveMap.get('base');
               for (String field :  obj.keySet()) {

                   if(obj.get(field) == null || DataUtil.getStringValue(obj.get(field)) == '') continue;

                   if(fbeanMap.containsKey(field) )aw.put(field, DataUtil.dataHandler(obj.get(field),fbeanMap.get(field).type.toUpperCase() ));

               }

            List<Object> saveList =(List<Object>) saveMap.get('datas');

   			List<AccessoryWarrantyDetails__c>details = new List<AccessoryWarrantyDetails__c>();
   			Set<String> eset = new Set<String>();

   			for (Object o  : saveList) {
   				Map<String,Object> mo = (Map<String,Object>)o;
   				AccessoryWarrantyDetails__c awd = new AccessoryWarrantyDetails__c();
   				awd.Id = DataUtil.getStringValue(mo.get('detailId'));
   				awd.Parts__c = DataUtil.getStringValue(mo.get('productId'));
   				//awd.P_N__c = DataUtil.getStringValue(mo.get('pn'));
          awd.Name = DataUtil.getStringValue(mo.get('productName'));

   				awd.DamagedPartsNumber__c = DataUtil.getStringValue(mo.get('originpn'));
   				awd.ReplaceSerialNumber__c = DataUtil.getStringValue(mo.get('replacepn'));
   				details.add(awd);
   				if(awd.Id != null )eset.add(awd.Id);
   			}

   			if( details.isEmpty() )throw new DmlException('请选择明细!');

   			SavePoint sp = Database.setSavepoint();
   			try {
   			    if(isNew) aw.Id = null;
   			    upsert aw ;

   			    delete [select Id from AccessoryWarrantyDetails__c where AccessoryWarranty__c=:aw.Id  and Id not in: eset  ];

   			    for (AccessoryWarrantyDetails__c awd :  details) {
   			    	
   			    	if(awd.Id == null ) awd.AccessoryWarranty__c = aw.Id;
   			    }
   			    upsert details ;
   			    isSuccess = true;
   			    msg = '保存成功!';
   			    backId = aw.Id;
   			}
   			catch (Exception e) {
   				Database.rollback(sp);
   		 		msg = '保存失败!'+e.getMessage()+e.getStackTraceString();   

   			}
   			
   		    
   		}catch (Exception e) {
   		 	msg = '保存失败!'+e.getMessage()+e.getStackTraceString();   
   		}
   		
   }
   	private List<ProductBean> getSearchs(){
   		List<ProductBean> tmp = new List<ProductBean>();

   		for (WorkOrderProduct__c wp  :[select Id ,Product__c ,Product__r.Name ,Product__r.Spec__c,
   			Product__r.SerialNo__c,Product__r.Model__c ,Product__r.Brand__c ,Product__r.NCCode__c,WarrantyNo__c 
   			from WorkOrderProduct__c where WorkOrder__c =:aw.RelatedWorkOrder__c and WarrantyNo__c > 0 
        and Product__r.Brand__c in:MaccuraBrandUtil.maccura and Product__r.Category0__c != '耗材' ] ) {
   			for(Decimal i = 0 ; i < wp.WarrantyNo__c ; i++){
                tmp.add(new ProductBean(wp));
            }
           
   		}
   		return tmp;
   	}
   	private List<ProductBean> getDetails(){
   		List<ProductBean> tmp = new List<ProductBean>();
   		for (AccessoryWarrantyDetails__c awd  :[select Id,DamagedPartsNumber__c ,ReplaceSerialNumber__c,Parts__c,
   			AccessoryWarranty__c,Parts__r.Name ,Parts__r.NCCode__c,Parts__r.Brand__c,Parts__r.SerialNo__c,Parts__r.Spec__c 
   		 from AccessoryWarrantyDetails__c where AccessoryWarranty__c =:backId] ) {
   			tmp.add(new ProductBean(awd));
   		}
   		return tmp;
   	}
    public void setNil(){
   		dataJson = '[]';
   		saveJson = '{}';
   		//searchJson = '{}';
   		 
   }

   public class ProductBean{
   		public String detailId ;
   		public String productId ;
   		public String productName;
   		//public String pn;
   		public String originpn;
   		public String replacepn;

   		public String spec ;
   		public String nccode ;
   		public String serialno ; 
         public String brand ;


   		public ProductBean(AccessoryWarrantyDetails__c awd ){
   			detailId = awd.Id;
   			productId = awd.Parts__c;
   			productName = awd.Parts__r.Name;
   			//pn = awd.P_N__c;
   			originpn = awd.DamagedPartsNumber__c;
   			replacepn = awd.ReplaceSerialNumber__c;

            spec = awd.Parts__r.Spec__c;
            nccode = awd.Parts__r.NCCode__c;
            serialno = awd.Parts__r.SerialNo__c;
            brand = awd.Parts__r.Brand__c;


   		}

   		public ProductBean(WorkOrderProduct__c prd ){
   			productId = prd.Product__c;
   			productName = prd.Product__r.Name;
   			spec = prd.Product__r.Spec__c;
   			nccode = prd.Product__r.NCCode__c;
   			serialno = prd.Product__r.SerialNo__c;


            brand = prd.Product__r.Brand__c;

   		}

   }



}